//
//  WorkViewController.m
//  运营管理系统
//
//  Created by 杨毅 on 16/9/21.
//  Copyright © 2016年 杨毅. All rights reserved.
//

#import "WorkViewController.h"
#import "workModel.h"
#import "WorkCell.h"
#import "ShowTimeViewController.h"
#import "GZupdataViewController.h"
#import "CountViewController.h"
#import "chuliListVC.h"
#import "AppDelegate.h"
#import "CarExtendVC.h"
#import "CarComeBackVC.h"
#import "CarExtendVC.h"
#import "CarShListVC.h"
#import "GZchuLiQRVC.h"
#import "CarBackQRVC.h"
#import <CoreLocation/CoreLocation.h>
#import "AFNetworking.h"
#import "UpListVC.h"
#import "ViewController.h"
#import "MBProgressHUD.h"
#import "YYFeedListVC.h"
#import "YYFeedBackConfirmVC.h"
#import "YYworkSuggestionVC.h"
@interface WorkViewController ()<UITableViewDelegate,UITableViewDataSource,CLLocationManagerDelegate>
{

     
    NSTimer *timer;
    NSString *_versionStr;
    NSString *_releaseNotes;
    /**
     故障上报
     故障审核
     故障处理
     故障处理确认
     巡检录入
     质量反馈
     质量反馈确认
     工作建议
     */
    
    UpListVC *_GZup;
    ShowTimeViewController *_showTime;
    chuliListVC *_chuli;
    GZchuLiQRVC *_CLQR;
    CountViewController *_XJRL;
    YYFeedListVC *_Feed;
    YYFeedBackConfirmVC *_FeedConfirm;
    YYworkSuggestionVC *_suggestionVC;
    
    NSString *_place;
    CGFloat lnt;
    CGFloat lat;
    CLLocationManager *_LocationManager; //定位管理器
    NSString *_errorContent;//异常内容
    NSString *_interError;
    

}

@property (nonatomic,strong)UITableView *tableview;
@property (nonatomic,strong)NSMutableArray *dataSource;
@property (nonatomic,strong)NSMutableArray *dataSource1;
@property (nonatomic,strong)AFHTTPSessionManager *Manager;

@end

@implementation WorkViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
    //3.字典从文件中读取数据
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:[self filePath]];
    if (dic != nil) {
        
        if (![[dic objectForKey:@"username"] isKindOfClass:[NSNull class]] && ![[dic objectForKey:@"password"] isKindOfClass:[NSNull class]]) {
            //1.找到UIApplication对象
            //表示当前正在运行的应用程序
            UIApplication *app = [UIApplication sharedApplication];
            //2.获取代理对象
            AppDelegate *delegate = app.delegate;
            //3.将数据保存到username属性中
            delegate.userId = [[dic objectForKey:@"userid"]integerValue];
            delegate.username = [dic objectForKey:@"username"];
            delegate.loginName = [dic objectForKey:@"password"];
            delegate.tel = [dic objectForKey:@"tel"];;
            delegate.level = [[dic objectForKey:@"lev"]integerValue];
            delegate.levelName = [dic objectForKey:@"levelN"];
            delegate.iconUrl = [dic objectForKey:@"iconurl"];
            delegate.upper = [[dic objectForKey:@"upper"]integerValue];
            delegate.email = [dic objectForKey:@"emailStr"];
            delegate.List = [dic objectForKey:@"list"];
            self.userID = [[dic objectForKey:@"userid"]integerValue];
            NSSLog(@"%ld",(long)self.userID);
            self.level = [[dic objectForKey:@"level"]integerValue];
            NSArray *arr = [dic objectForKey:@"list"];
            
            _dataSource1 = [[NSMutableArray alloc]init];
            for (NSInteger i = 0; i <arr.count; i++) {
                if ([arr[i]integerValue] < 6) {
                    [_dataSource1 addObject:arr[i]];
                }else if ([arr[i]integerValue] == 11 || [arr[i]integerValue] == 12){
                    [_dataSource1 addObject:arr[i]];
                }
            }
            [_dataSource1 addObject:@13];
            _dataSource = [[NSMutableArray alloc]initWithArray:[workModel WorkModule:_dataSource1]];
            //NSSLog(@"%@",[dic objectForKey:@"username"]);
        }

    }

    //判断网络状态
    [self checkInternetMethod];

}
- (void)dingwei{
    //实例化定位管理器
    _LocationManager = [[CLLocationManager alloc] init];
    
    _LocationManager.delegate = self;
    
    //请求用户同意定位
    //只在前台定位
    //在项目的配置文件Info.plist中添加以下内容
    //NSLocationWhenInUseUsageDescription
    if ([[[UIDevice currentDevice] systemVersion] doubleValue] > 8.0) {
        [_LocationManager requestAlwaysAuthorization];
    }
    
    //允许在后台定位
    //NSLocationAlwaysUsageDescription
    //[_manager requestAlwaysAuthorization];
    
    //设置定位的精度和更新频率
    /*
     kCLLocationAccuracyBestForNavigation  导航
     kCLLocationAccuracyBest;              较好的精度
     kCLLocationAccuracyNearestTenMeters;  10米
     kCLLocationAccuracyHundredMeters;     100米
     kCLLocationAccuracyKilometer;         1000米
     kCLLocationAccuracyThreeKilometers;   3000米
     */
    _LocationManager.desiredAccuracy = kCLLocationAccuracyBest; //定位的精度
    
    _LocationManager.distanceFilter = 100; //更新频率
    if ([CLLocationManager locationServicesEnabled]) { // 判断是否打开了位置服务
        //启动定位
        [_LocationManager startUpdatingLocation]; // 开始更新位置
    }else{
        
    }

}
////网络判断
- (void)checkInternetMethod{
    
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager startMonitoring];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (status == AFNetworkReachabilityStatusReachableViaWiFi || status ==AFNetworkReachabilityStatusReachableViaWWAN) {
            NSSLog(@"网络连接正常");
            
        }else{
            _interError = @"网络异常";
            [self showAlert:@"温馨提示" message:@"请检查您的网络" actionWithTitle:@"我知道了"];
        }
    }];
}
- (AFHTTPSessionManager *)Manager{
    if (!_Manager) {
        _Manager = [AFHTTPSessionManager manager];
    }
    return _Manager;
}

//获取文件路径
- (NSString *)filePath{
    //1.获取Document(存放持久保存的数据)文件夹路径
    //参数1:查找的文件路径
    //参数2:在那个域中查找
    //参数3:是否显示详细路径
    NSString *doucumentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    //2.拼接上文件路径
    NSString *filtPath = [doucumentsPath stringByAppendingPathComponent:@"Log.txt"];
    //NSLog(@"%@",filtPath);
    return filtPath;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"工作";
    self.view.backgroundColor = [UIColor whiteColor];
    self.tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH, kSCREEN_HEIGHT) style:UITableViewStylePlain];
    self.tableview.backgroundColor = UIColorFromRGB(0xf0f0f0);
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    self.tableview.rowHeight = 60;
    //去掉多余的cell
    UIView *v = [[UIView alloc] initWithFrame:CGRectZero];
    //v.backgroundColor = UIColorFromRGB(0xf0f0f0);
    [self.tableview setTableFooterView:v];
    [self.view addSubview:self.tableview];
    
    UINib *nib = [UINib nibWithNibName:@"WorkCell" bundle:nil];
    [self.tableview registerNib:nib forCellReuseIdentifier:@"cell"];

//5分钟传一次用户位置
    timer = [NSTimer scheduledTimerWithTimeInterval:300.0 target:self selector:@selector(myLog) userInfo:nil repeats:YES];
    [timer setFireDate:[NSDate distantPast]];

    
}
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{

    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
            if ([_LocationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
                
                [_LocationManager requestWhenInUseAuthorization];     //NSLocationWhenInUseDescription
                [_LocationManager requestAlwaysAuthorization];
            }
            break;
        default:
            break;
            
            
    }
}
/** 不能获取位置信息时调用*/
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSSLog(@"%@",error);

}
//定时执行定位
- (void)myLog{

//    [_LocationManager startUpdatingLocation];
    [self dingwei];


}
//定位成功后会执行的函数
- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray *)locations
{
    
    CLLocation *currentLocation = [locations firstObject];
    //NSLog(@"%@",currentLocation);
    
    CLLocation *newLocation = locations[0];
    CLLocationCoordinate2D oldCoordinate = newLocation.coordinate;


    //        NSLog(@"经度：%f,纬度：%f",newCoordinate.longitude,newCoordinate.latitude);
    //获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *array, NSError *error)
     {
         
         if (array.count > 0)
         {
             CLPlacemark *placemark = [array firstObject];
             
             //NSLog(@"%@",placemark.name);//具体位置
             //获取城市
             NSString *city = placemark.locality;
             if (!city) {
                 //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                 city = placemark.administrativeArea;
             }
             NSString  *cityName = city;
             NSLog(@"定位完成:%@",cityName);
             //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
             NSMutableString *str = [[NSMutableString alloc]init];
             [str appendString:placemark.administrativeArea];
             if (placemark.locality.length>0){
                 [str appendString:placemark.locality];
             }
             if (placemark.subLocality.length>0) {
                 [str appendString:placemark.subLocality];
             }
             if (placemark.thoroughfare.length>0) {
                 [str appendString:placemark.thoroughfare];
             }
             if (placemark.subThoroughfare.length>0) {
                 [str appendString:placemark.subThoroughfare];
             }
             _place = str;//城市地区街道子街道
             
             self.Manager.responseSerializer = [AFHTTPResponseSerializer serializer];
             [_Manager POST:K_LatAndLnt parameters:@{userid:[NSString stringWithFormat:@"%ld",self.userID],Lnt:[NSString stringWithFormat:@"%f",oldCoordinate.longitude],Lat:[NSString stringWithFormat:@"%f",oldCoordinate.latitude],Adress:_place} progress:^(NSProgress * _Nonnull uploadProgress) {
                 
             } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                 
             } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                 
             }];
             
             
             NSUserDefaults *userdefaults = [NSUserDefaults standardUserDefaults];
             [userdefaults setFloat:oldCoordinate.latitude forKey:@"lat"];
             [userdefaults setFloat:oldCoordinate.longitude forKey:@"lnt"];
             [userdefaults setObject:_place forKey:@"adress"];
             
             
         }else if (error == nil && [array count] == 0)
         {
             NSLog(@"No results were returned.");
         }else if (error != nil)
         {
             NSLog(@"An error occurred = %@", error);
         }
     }];
    
    
    [manager stopUpdatingLocation];
    
}


#pragma mark-->tableviewdelegate


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return _dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WorkCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    workModel *model = _dataSource[indexPath.row];
       
       [cell fillCellWithModel:model];
       return cell;
       
   


    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //故障上报
    _GZup = [[UpListVC alloc]init];
    //故障审核
    _showTime = [[ShowTimeViewController alloc]init];
    //故障处理
    _chuli = [[chuliListVC alloc]init];
    //故障处理确认
    _CLQR = [[GZchuLiQRVC alloc]init];
    //巡检录入
    _XJRL = [[CountViewController alloc]init];
    //质量反馈
    _Feed = [[YYFeedListVC alloc]init];
    //质量反馈确认
    _FeedConfirm = [[YYFeedBackConfirmVC alloc]init];
    _suggestionVC = [[YYworkSuggestionVC alloc]init];
    workModel *model = _dataSource[indexPath.row];
    switch (model.LevelTag) {
        case 1:
            [self.navigationController pushViewController:_GZup animated:YES];
            break;
        case 2:
            [self.navigationController pushViewController:_showTime animated:YES];
            break;
        case 3:
            [self.navigationController pushViewController:_chuli animated:YES];
            break;
        case 4:
            [self.navigationController pushViewController:_CLQR animated:YES];
            break;
        case 5:
            [self.navigationController pushViewController:_XJRL animated:YES];
            break;
        
        case 11:
            [self.navigationController pushViewController:_Feed animated:YES];
            break;
        case 12:
            [self.navigationController pushViewController:_FeedConfirm animated:YES];
            break;
        case 13:
            [self.navigationController pushViewController:_suggestionVC animated:NO];
            break;
        default:
            break;
    }
    
}
#pragma mark 封装提示框
-(void)showAlert:(NSString *)Title message:(NSString *)message actionWithTitle:(NSString *)actionWithTitle{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:Title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:actionWithTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}


@end
